package com.aviccxzx.smarthome.UserModule;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.aviccxzx.smarthome.DeviceModule.GosDeviceModuleBaseActivity;
import com.aviccxzx.smarthome.MsgID;
import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.entity.DeleteDevMove;
import com.aviccxzx.smarthome.entity.DoorMsg;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.netutil.msg.MsgCenter;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.utils.ChangeNameDialogUtil;
import com.aviccxzx.smarthome.utils.DensityUtil;
import com.aviccxzx.smarthome.utils.DialogUtil;
import com.aviccxzx.smarthome.view.TextMoveLayout;
import com.gizwits.gizwifisdk.api.GizWifiCentralControlDevice;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.gizwits.gizwifisdk.enumration.GizDeviceSharingUserRole;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.gizwifisdk.listener.GizWifiCentralControlDeviceListener;
import com.gizwits.gizwifisdk.listener.GizWifiDeviceListener;
import com.gizwits.gizwifisdk.listener.GizWifiSDKListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.aviccxzx.smarthome.fragment.DeviceListFragment.isFromDeviceList;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.mDevice;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.subList;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.tagSet;


/**
 * Created by joey on 206/11/17.
 */
public class GasActivity extends GosDeviceModuleBaseActivity implements View.OnClickListener {
    TextView door_name, title_name_tv, door_electricity, door_mac;
    String name = "";
    String macaddress = "";
    String netStatus = "";
    boolean alarm;
    String pos = "";
    ListView doormsg_list;
    DoorAdapter adapter = null;
    List<DoorMsg.DataBean> msgList1 = null;
    List<DoorMsg.DataBean> msgList = new ArrayList<>();
    GizWifiDevice mdevice = null;
    private SeekBar mSeekbar_rate = null;
    private LinearLayout ll_parent_rate;
    private TextView mTvMax;
    private int screenWidth;//屏幕宽度
    private TextMoveLayout textMoveLayout;
    CheckBox gas_switch = null;
    TextView gas_switch_tv, alarm_state, gas_value_tv;
    RelativeLayout set_gasvalue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setContentView(R.layout.gas_lay_v19);
        } else {
        }
        initView();
        getHistory();
    }

    private void getHistory() {
        progressDialog.show();
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<DoorMsg> call = service.getDataHistory(macaddress);
        call.enqueue(new Callback<DoorMsg>() {
            @Override
            public void onResponse(Call<DoorMsg> call, Response<DoorMsg> response) {
                if (response.body() != null && response.body().getData() != null)
                    msgList1 = response.body().getData();
                if (msgList1 != null && msgList1.size() > 0) {
                    for (DoorMsg.DataBean data : msgList1) {
                        if (data.getValue().equals("1")) {
                            msgList.add(data);
                        }
                    }
                    adapter = new DoorAdapter();
                    doormsg_list.setAdapter(adapter);
                    progressDialog.dismiss();
                } else {
                    App.getApp().showToast("没有历史消息");
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onFailure(Call<DoorMsg> call, Throwable t) {
                progressDialog.dismiss();
            }
        });

    }

    private void initView() {
        findViewById(R.id.ll_title_left_view).setOnClickListener(this);
        findViewById(R.id.gas_on).setOnClickListener(this);
        set_gasvalue = (RelativeLayout) findViewById(R.id.set_gasvalue);
        door_name = (TextView) findViewById(R.id.door_name);
        door_electricity = (TextView) findViewById(R.id.door_electricity);
        title_name_tv = (TextView) findViewById(R.id.title_name_tv);
        doormsg_list = (ListView) findViewById(R.id.doormsg_list);
        gas_switch = (CheckBox) findViewById(R.id.gas_switch);
        gas_switch_tv = (TextView) findViewById(R.id.gas_switch_tv);
        alarm_state = (TextView) findViewById(R.id.alarm_state);
        gas_value_tv = (TextView) findViewById(R.id.gas_value_tv);
        //点击修改名称
        findViewById(R.id.device_info).setOnClickListener(this);
        findViewById(R.id.change_devicename).setOnClickListener(this);
        findViewById(R.id.delete_doorlock).setOnClickListener(this);
        findViewById(R.id.recom_gas).setOnClickListener(this);
        netStatus = getIntent().getStringExtra("netStatus");
        name = getIntent().getStringExtra("deviceName");
        macaddress = getIntent().getStringExtra("deviceMac");
        alarm = getIntent().getBooleanExtra("alarm", false);
        door_mac = (TextView) findViewById(R.id.door_mac);
        door_mac.setText(macaddress);
        if(!TextUtils.isEmpty(netStatus)){
            alarm_state.setText("掉线");
            alarm_state.setTextColor(getResources().getColor(R.color.red));
        }
        if (alarm) {
            alarm_state.setText("异常报警");
            alarm_state.setTextColor(getResources().getColor(R.color.red));

            gas_switch.setChecked(true);
        }
        if (!TextUtils.isEmpty(name)) {
            title_name_tv.setText(name);
            door_name.setText(name);
        }
        screenWidth = getWindowManager().getDefaultDisplay().getWidth();
        mTvMax = (TextView) findViewById(R.id.tv_max);
        textMoveLayout = (TextMoveLayout) findViewById(R.id.textLayout);
        mSeekbar_rate = (SeekBar) findViewById(R.id.seekbar_rate);
        ll_parent_rate = (LinearLayout) findViewById(R.id.ll_parent_rate);
        for (GizWifiDevice device : subList) {
            if (device.getMacAddress().equals(macaddress)) {
                mdevice = device;
            }
        }
        if (mdevice != null) {
            //订阅设备
            //监听上报
            mdevice.setSubscribe(MsgID.PS_GAS, true);
            mdevice.setListener(subListener);
        }
    }

    // 订阅实现回调
    GizWifiDeviceListener subListener = new GizWifiDeviceListener() {
        @Override
        public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice
                device, boolean isSubscribed) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                // 订阅或解除订阅成功
                mdevice.getDeviceStatus(null);
                mdevice.setListener(deviceListener);
            } else {
                // 失败
            }
        }
    };
    int threshold;
    boolean standard;
    boolean getVersion = false;//判断是否获取到数据点信息
    /**
     * 获取上报的设备信息
     */
    private GizWifiDeviceListener deviceListener = new GizWifiDeviceListener() {
        @Override
        public void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, Object> dataMap, int sn) {
            super.didReceiveData(result, device, dataMap, sn);
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                if (dataMap.get("data") != null) {
                    ConcurrentHashMap<String, Object> map = (ConcurrentHashMap<String, Object>) dataMap.get("data");
                    byte[] hard = (byte[]) map.get("HardWareVersion");
                    String hardVi = new String(hard);
                    if (hardVi.endsWith("0")) {
                        //专业版 显示灵敏度调节
                        set_gasvalue.setVisibility(View.VISIBLE);
                        standard = false;
                    } else {
                        //标准版
                        set_gasvalue.setVisibility(View.GONE);
                        standard = true;
                    }
                    getVersion = true;
                    //燃气浓度
                    int concentration = (int) map.get("Concentration");
                    gas_value_tv.setText(concentration + "");
                    //报警阈值
                    threshold = (int) map.get("Threshold") / 500;
                    recommend = true;
                    new SeekBarUtil_rate(mSeekbar_rate, ll_parent_rate, mTvMax, screenWidth, GasActivity.this, textMoveLayout, false);
                    //报警状态
                    Boolean gasState = (Boolean) map.get("AlarmStatus");
                    if (gasState != null && gasState) {
                        alarm_state.setText("异常报警");
                        alarm_state.setTextColor(getResources().getColor(R.color.red));

                        gas_switch.setChecked(true);
                    } else {
                        alarm_state.setText("正常");
                        alarm_state.setTextColor(getResources().getColor(R.color.white));

                        gas_switch.setChecked(false);
                    }
                }
            }
        }
    };


    boolean recommend = false;
    String deviceName, uid, token = "";

    @Override
    public void onClick(View view) {
        uid = spf.getString("Uid", "");
        token = spf.getString("Token", "");
        switch (view.getId()) {
            case R.id.ll_title_left_view:
                finish();
                break;
            case R.id.device_info:
                if (getVersion) {
                    Intent intent = new Intent(this, DeviceInfoActivity.class);
                    intent.putExtra("id", macaddress);
                    intent.putExtra("standard", standard);
                    intent.putExtra("class", 2);
                    startActivity(intent);
                } else {
                    App.getApp().showToast("稍等几秒钟，设备正在启动中");
                }

                break;
            case R.id.gas_on:
                if (gas_switch.isChecked()) {
                    //解除报警
                    ConcurrentHashMap<String, Object> data = new ConcurrentHashMap<>();
                    data.put("CancelAlarm", true);
                    mdevice.write(data, 1);
                    mdevice.setListener(getListener);
                    progressDialog.show();
                }
                break;
            case R.id.recom_gas:
                //推荐灵敏度设置
                recommend = true;
                threshold = 0;
                new SeekBarUtil_rate(mSeekbar_rate, ll_parent_rate, mTvMax, screenWidth, GasActivity.this, textMoveLayout, false);
                ConcurrentHashMap<String, Object> dataMap = new ConcurrentHashMap<>();
                dataMap.put("Threshold", 8 * 500);
                mdevice.write(dataMap, 0);
                mdevice.setListener(getListener);
                progressDialog.show();
                break;
            case R.id.change_devicename:
                new ChangeNameDialogUtil(GasActivity.this, "修改设备名称", new ChangeNameDialogUtil.SureInterfance() {
                    @Override
                    public void sureTodo(String name) {
                        //确定修改 处理方案
                        App.getApp().showToast(name);
                        deviceName = name;
                        mdevice.setCustomInfo("", name);
                        mdevice.setListener(getGizWifiDeviceListener());
                        progressDialog.show();
                    }
                }).showSelfDialog();
                break;
            case R.id.delete_doorlock:
                    new DialogUtil(GasActivity.this, true, true, "确认删除子设备吗", "取消", "确定", new DialogUtil.SureInterfance() {
                        @Override
                        public void sureTodo() {
                            if (mdevice.getSharingRole() != null && mdevice.getSharingRole().equals(GizDeviceSharingUserRole.GizDeviceSharingGuest)) {
                                deleteMove(0);
                            } else {
                                deleteMove(1);
                            }
                        }

                        @Override
                        public void cancle() {

                        }
                    }).showCustomDialog();
                break;
        }
    }

    // 实现回调
    GizWifiDeviceListener getListener = new GizWifiDeviceListener() {
        @Override
        public void didReceiveData(GizWifiErrorCode result, GizWifiDevice
                device, ConcurrentHashMap<String, Object> dataMap, int sn) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                if (sn == 0) {
                    // 浓度设置成功
                } else if (sn == 1) {
                    // 解除报警成功
                    alarm_state.setText("正常");
                    alarm_state.setTextColor(getResources().getColor(R.color.white));

                    gas_switch.setChecked(false);
                }
                MsgCenter.fireNull("update_alarm", mdevice.getMacAddress());
            } else {
                if (sn == 0) {
                    //恢复之前的初试浓度
                }
                if (sn == 1) {
                    alarm_state.setText("异常报警");
                    alarm_state.setTextColor(getResources().getColor(R.color.red));

                    gas_switch.setChecked(true);
                }
                MsgCenter.fireNull("update_alarmset", mdevice.getMacAddress());
            }
            progressDialog.dismiss();
        }
    };

    /**
     * 修改名字回调
     *
     * @param result 错误码
     * @param device 当前设备
     */
    @Override
    public void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) {
        super.didSetCustomInfo(result, device);
        progressDialog.dismiss();
        if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
            // 修改成功
            App.getApp().showToast("修改成功");
            door_name.setText(deviceName);
        } else {
            //修改失败
            App.getApp().showToast("修改失败");
        }
    }

    // 实现回调
    GizWifiDeviceListener mListener = new
            GizWifiCentralControlDeviceListener() {
                @Override
                public void didUpdateSubDevices(GizWifiCentralControlDevice device, GizWifiErrorCode result,
                                                List<GizWifiDevice> subDeviceList) {
                    if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS || result == GizWifiErrorCode.GIZ_SDK_SUBDEVICE_INVALID) {
                        // 删除成功
                        GizWifiSDK.sharedInstance().setListener(unbindListener);
                        GizWifiSDK.sharedInstance().unbindDevice(uid, token,
                                mdevice.getDid());
                    } else {
                        // 删除失败
//                        progressDialog.dismiss();
//                        App.getApp().showToast("网络延迟，请稍候再试");

                        GizWifiSDK.sharedInstance().setListener(unbindListener);
                        GizWifiSDK.sharedInstance().unbindDevice(uid, token,
                                mdevice.getDid());
                    }
                }
            };
    GizWifiSDKListener unbindListener = new GizWifiSDKListener() {
        @Override
        public void didUnbindDevice(GizWifiErrorCode result, String did) {
            super.didUnbindDevice(result, did);
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                isFromDeviceList = false;
                tagSet.remove(mdevice.getMacAddress());
                tagSet.add(uid);
                JPushInterface.setTags(GasActivity.this, 0, tagSet);
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        /**
                         *要执行的操作
                         */
                        finish();
                    }
                }, 2000);
            } else {
                // 解绑失败
                progressDialog.dismiss();
                App.getApp().showToast("删除失败，请稍候重试");
            }
        }
    };


    public void deleteMove(int admin) {
        progressDialog.show();
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<DeleteDevMove> call = service.unbundSub(mdevice.getMacAddress(), admin);
        call.enqueue(new Callback<DeleteDevMove>() {
            @Override
            public void onResponse(Call<DeleteDevMove> call, Response<DeleteDevMove> response) {
                if (response != null && response.body() != null) {
                    int code = response.body().getCode();
                    if (code == 4) {
                        if (mdevice.getSharingRole() != null && mdevice.getSharingRole().equals(GizDeviceSharingUserRole.GizDeviceSharingGuest)) {
                            //分享的设备只解绑不删除
                            GizWifiSDK.sharedInstance().setListener(unbindListener);
                            GizWifiSDK.sharedInstance().unbindDevice(uid, token,
                                    mdevice.getDid());
                        } else {
                            mDevice.setListener(mListener);
                            mDevice.deleteSubDevice(mdevice);
                        }

                        tagSet.remove(mdevice.getMacAddress());
                        JPushInterface.setTags(GasActivity.this, 0, tagSet);
                    } else {
                        progressDialog.dismiss();
                        App.getApp().showToast("接口删除失败");
                    }
                }
            }

            @Override
            public void onFailure(Call<DeleteDevMove> call, Throwable t) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mdevice != null) {
            mdevice.setSubscribe(MsgID.PS_GAS, false);
        }
    }

    public class SeekBarUtil_rate {
        private SeekBar mSeekbar = null;
        private TextView moveText;

        private int screenWidth;//屏幕宽度
        private ViewGroup.LayoutParams layoutParams;

        private int mLeftMargin, pro;
        private TextPaint mPaint;
        private TextView mTvMax;
        private LinearLayout mParentView;
        private Boolean firstIn = false;
        private TextMoveLayout textMoveLayout;
        private Context mContext;

        public SeekBarUtil_rate(SeekBar mSeekbar, LinearLayout mParentView, TextView mTvMax, int screenWidth, Context mContext, TextMoveLayout textMoveLayout, boolean first) {
            this.mSeekbar = mSeekbar;
            this.mParentView = mParentView;
            this.mTvMax = mTvMax;
            this.screenWidth = screenWidth;
            this.mContext = mContext;
            this.textMoveLayout = textMoveLayout;
            firstIn = first;
            setSeekBarValues();
            setMoveTextView();
            getChildenLayoutParams();
        }


        /**
         * 设置moveTextView的基础参数
         */
        private void setMoveTextView() {

            moveText = new TextView(mContext);
            moveText.setText(3 + "%");
            moveText.setTextColor(Color.rgb(0, 161, 229));
            moveText.setTextSize(16);

            layoutParams = new ViewGroup.LayoutParams(screenWidth, 50);

            textMoveLayout = (TextMoveLayout) findViewById(R.id.textLayout);

            textMoveLayout.addView(moveText, layoutParams);
            moveText.layout(5, 20, screenWidth, 80);
        }

        /**
         * 获取子view的marginLayoutParams
         */
        private void getChildenLayoutParams() {
            View childAt = mParentView.getChildAt(0);
            ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) childAt.getLayoutParams();
            mLeftMargin = marginLayoutParams.leftMargin;
            mSeekbar.setOnSeekBarChangeListener(new SeekBarUtil_rate.OnSeekBarChangeListenerImp());
        }

        /**
         * 设置seekbar的基础参数
         */
        public void setSeekBarValues() {

            //        mTvMax.setText("100");
            mSeekbar.setEnabled(true);
            mSeekbar.setMax(22);
            if (recommend) {
                if (threshold != 0) {
                    mSeekbar.setProgress(threshold);
                    mTvMax.setText(threshold + "%");
                } else {
                    mSeekbar.setProgress(8);
                    mTvMax.setText(8 + "%");
                }

            } else {
                mSeekbar.setProgress(25);
            }
        }

        /**
         * seekbar滑动监听
         */
        private class OnSeekBarChangeListenerImp implements
                SeekBar.OnSeekBarChangeListener {

            // 触发操作，拖动
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                setMoveTextLayout(progress + 3);
            }

            // 开始拖动时候触发的操作
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            // 停止拖动时候
            public void onStopTrackingTouch(SeekBar seekBar) {
                ConcurrentHashMap<String, Object> dataMap = new ConcurrentHashMap<>();
                int progress = seekBar.getProgress();
                dataMap.put("Threshold", (progress + 3) * 500);
                mdevice.write(dataMap, 0);
                mdevice.setListener(getListener);
                progressDialog.show();
            }
        }

        /**
         * seekbar滑动过程中改变moveTextView的位置
         */
        public void setMoveTextLayout(int newPro) {
            if (mPaint == null) {
                mPaint = new TextPaint();
            }

            float measureText = mPaint.measureText(moveText.getText().toString().trim());
            Rect bounds = mSeekbar.getProgressDrawable().getBounds();
            int xFloat = (int) (bounds.width() * mSeekbar.getProgress() / mSeekbar.getMax() - measureText / 2 + DensityUtil.px2dip(mContext, mLeftMargin));
            if (firstIn) {
                firstIn = false;
                moveText.layout(624, 20, screenWidth, 80);
                moveText.setText(25 + "%");
                mTvMax.setText(25 + "%");
            } else {
                moveText.layout(xFloat, 20, screenWidth, 80);
                if (recommend) {
                    recommend = false;
                    if (threshold != 0) {
                        moveText.setText(threshold + "%");
                        mTvMax.setText(threshold + "%");
                    } else {
                        moveText.setText(8 + "%");
                        mTvMax.setText(8 + "%");
                    }
                } else {
                    moveText.setText(mSeekbar.getProgress() + "%");
                    mTvMax.setText(mSeekbar.getProgress() + 3 + "%");
                }
            }
        }
    }


    HashMap<Integer, View> mHashMap = new HashMap<>();

    public class DoorAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return msgList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {
            ViewHolder holder = null;
            if (mHashMap.get(i) == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(GasActivity.this).inflate(R.layout.doormsg_listitem_lay, viewGroup, false);
                mHashMap.put(i, convertView);
                convertView.setTag(holder);
            } else {
                convertView = mHashMap.get(i);
                holder = (ViewHolder) convertView.getTag();
            }

            holder.msg_name = (TextView) convertView.findViewById(R.id.msg_name);
            holder.msg_time = (TextView) convertView.findViewById(R.id.msg_time);

            DoorMsg.DataBean data = msgList.get(i);
            if (data != null) {
                holder.msg_name.setText("可燃气报警器报警");
                holder.msg_time.setText(data.getCtime());
            }
            progressDialog.dismiss();
            return convertView;
        }

        public class ViewHolder {
            TextView msg_name, msg_time;
        }
    }
}
